<style scoped lang="less">
.password-box {
    height: 100vh;
    display: flex;
    align-items: center;
    background-color: #eef1f6;

    .logo {
        text-align: center;
        font-size: 32px;
        margin-bottom: 20px;
    }

    .app-logo {
        fill: var(--el-color-primary);
        width: 80px;
        height: 80px;
        vertical-align: middle;
        margin-right: 10px;
    }

    .password-box-wrapper {
        width: 100%;
    }

    .password-inner {
        width: 500px;
        margin: auto;
        background-color: #fff;
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        overflow: hidden;
    }

    .title {
        background-color: var(--el-color-primary);
        color: #fff;
        padding: 20px;
    }

    .box-wrapper {
        padding: 40px 50px 50px;
    }

    .box-inner {
        margin-top: 10px;
        display: flex;
    }
}

.share-file-content-box {

    .share-info {
        display: flex;
        margin-bottom: 20px;

    }

    .file-title {
        margin-right: 20px;
    }

    .other-info {
        margin-right: 20px;
    }

    .actions {

    }
}

.share-main {
    padding-top: 50px;
}

.share-content-wrapper {
    height: 100vh;
    background: #efefef;
}

.share-file-wrapper {
    max-width: 1200px;
    margin: auto;
    background: #fff;
    padding: 50px;
    border-radius: 5px;
}

.list-file-info {
    display: flex;
    line-height: 40px;
    height: 40px;
}

.list-file-icon {
    width: 40px;
    display: flex;
    align-items: center;
}

.list-file-name {
    margin-left: 5px;
}

.file-type-folder {
    cursor: pointer;
}
</style>
<template>
    <div class="page-share">
        <div v-if="loadingData">
            加载中...
        </div>
        <div v-else class="share-content-wrapper">
            <!-- 分享信息有误 -->
            <el-result v-if="shareError" icon="warning" sub-title="啊哦！没有找到分享数据，请打开正确的分享链接!">
            </el-result>
            <div v-else class="share-main">
                <!-- 显示分享信息 -->
                <div v-if="passwordBox.show" class="password-box">
                    <div class="password-box-wrapper">
                        <div class="logo">
                            <app-logo class="app-logo"/>
                            <span>天牛网盘</span>
                        </div>
                        <div class="password-inner">
                            <div class="title">
                                <el-avatar :size="30" :src="shareUser.avatar" style="vertical-align: middle"/>
                                <span style="margin-left: 3px">{{ shareUser.nickname }} 给您加密分享了文件</span>
                            </div>
                            <div class="box-wrapper">
                                <div style="font-size: 14px;">请输入提取密码：</div>
                                <div class="box-inner">
                                    <el-input v-model="passwordBox.value"/>
                                    <el-button :disabled="passwordBox.value.length == 0" @click="submitView"
                                               style="margin-left: 10px;width: 100px"
                                               type="primary">提取
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-else class="share-file-wrapper">
                    <div class="share-file-content-box">
                        <div class="share-info">
                            <div class="file-title">{{ shareInfo.title }}</div>
                            <div class="other-info">
                                <span>{{ formatDate(shareInfo.createTime, 'YYYY-MM-DD HH:mm') }}</span>
                                <span>{{ shareInfo.live == -1 ? '长期有效' : (shareInfo.live / 3600 / 24 + '天') }}</span>
                            </div>
                            <div class="actions">
                                <el-button @click="downloadSelect">下载</el-button>
                            </div>
                        </div>
                        <div>
                            <el-link v-if="$route.query.path && $route.query.path != '/'" @click="$router.back()">
                                返回上一级
                            </el-link>
                        </div>
                        <el-table ref="fileTable" :data="fileListData" style="width: 100%" @selection-change="onTableSelect">
                            <el-table-column type="selection"/>
                            <el-table-column label="名称">
                                <!-- 自定义单元格内容 -->
                                <template #default="file">
                                    <div class="list-file-info" :class="'file-type-' + file.row.type"
                                         @click="showChild(file.row)">
                                        <FileIcon class="list-file-icon" style="width: 40px;" :file="file.row"
                                                  :ext="file.row.type"/>
                                        <span class="list-file-name">{{ file.row.name }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="size" label="大小" width="200">
                                <template #default="file">
                                    <span class="list-file-size">{{ formatSize(file.row.size) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="创建时间" width="200">
                                <template #default="file">
                                    <span class="list-file-time">{{
                                            formatDate(file.row.createTime, 'YYYY-MM-DD HH:mm')
                                        }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {useRoute, useRouter} from "vue-router";
import api from "../service/api";
import {reactive, ref, watchEffect} from "vue";
import AppLogo from "../components/AppLogo.vue";
import {ElMessage} from "element-plus";
import strings from "../service/strings";
import FileIcon from "../components/FileIcon.vue";

export default {
    name: "Share",
    components: {AppLogo, FileIcon},
    setup(props, ctx) {
        const route = useRoute();
        const id = route.params.id // 获取动态路由的参数 实例: this.$route.params.id
        /**
         * 分享信息有误
         */
        const shareError = ref(false)
        /**
         * 是否加载中
         */
        const loadingData = ref(true)
        /**
         * 分享信息
         * @type {Ref<UnwrapRef<ShareInfo>>}
         */
        const shareInfo = ref({})
        /**
         * 所有的文件数组
         */
        const fileListData = ref([])
        /**
         *
         * @type {Ref<UnwrapRef<UserInfo>>}
         */
        const shareUser = ref({})
        const passwordBox = reactive({
            show: false,
            value: ''
        })
        const selectRows = ref([])
        // 分享密码保存的key
        const authId = "net_driver_share_auth_" + id;
        // 显示文件
        const showShareFiles = async (path = '/') => {
            try {

                const currentPath = route.query.path || '/';
                const result = await api.share.list(id, currentPath, passwordBox.value);
                fileListData.value = result
            } catch (e) {
                ElMessage(e.message)
                if (e.code && e.code == 1002) { // 密码错误
                    throw  e;
                }
            }
        }

        const inited = ref(false)

        // 使用参数加载分享
        api.share.info(id).then(ret => {
            if (null == ret) shareError.value = true
            else {

                const {share, user} = ret
                // 正确则显示分享信息
                shareInfo.value = share
                shareUser.value = user

                // 需要输入密码 且本地没有保存的密码数据
                if (ret.share.password && !sessionStorage.getItem(authId)) {
                    // 显示密码输入框
                    passwordBox.show = true
                    document.title = '天牛网盘 请输入提取密码'
                } else {
                    inited.value = true
                    passwordBox.value = sessionStorage.getItem(authId)
                    // showShareFiles()
                }
                // 开始加载文件
                //
            }
        }).catch(e => {
            shareError.value = true
        })
            .finally(() => {
                // 加载状态设置为false
                loadingData.value = false
            });
        // 提交密码
        const submitView = () => {
            if (!passwordBox.value) return;
            // 没有必要单独验证密码是否正确
            // 直接使用密码 加载文件
            showShareFiles().then(() => {
                // 如果能够加载成功文件 说明密码正确
                // 存储密码
                sessionStorage.setItem(authId, passwordBox.value)
                // 隐藏密码输入框
                passwordBox.show = false
                inited.value = true
            }).catch(e => console.log(e.message));
        }
        const router = useRouter()
        // 监视路径变化 加载对应的文件
        watchEffect(() => {
            if(inited.value){
                showShareFiles()
            }
        })
        // 显示下一级目录
        const showChild = (file) => {
            if (file.type != 'folder') return
            const currentPath = route.query.path || '';
            router.push('?path=' + currentPath + '/' + file.name)
        };
        const fileTable = ref()
        const downloadSelect = () => {
            // 1.直接通过文件编号构建下载链接(今天使用)
            // 2.通过文件编号创建下载任务，然后再下载(更好)
            // console.log()
            const url = 'http://localhost:8080/download?id='
            const idArr = [];
            fileTable.value.getSelectionRows().forEach(f => idArr.push(f.id));
            // const idList = fileTable.value.getSelectionRows().map(f=>f.id)
            // console.log(idArr,idList)
            location.href = url + idArr.join(',')

        }
        const onTableSelect = () =>{

        };
        return {
            shareError, loadingData, shareInfo, passwordBox, shareUser,
            submitView, fileListData, showChild, fileTable,onTableSelect,
            ...strings, downloadSelect
        }
    }
}
</script>
